<?php
class Delivery_Model_Cliente
	extends Delivery_Model_Abstract
{
	
	public $idCliente;
	// usados para el login
	public $email;
	public $clave;
	
	public $nombre;
	public $apellido;
	public $telefono;	
	public $activo;
	public $codigo;
	public $cantidadPedidos;
	public $fbUserId;
			
	protected $_direcciones;
	
	
	/**
	 * @param codigo: codigo de activacion
	 * @return bool
	 */
	public function activar( $code )
	{
		if( $this->estaActivo() ){
			throw new Delivery_Model_Exception( Delivery_Model_Exception::USER_ALREADY_ACTIVE );
		}
		
		if(  $this->codigo != $code ){
			throw new Delivery_Model_Exception( Delivery_Model_Exception::USER_INVALID_ACTIVATION_CODE );	
		}	
			
		$this->activo = 1;
		$this->codigo = null;
	}
	
	
	/**
	 * @return bool
	 */
	public function estaActivo()
	{
		return (bool) $this->activo;
	}
	
	
	/**
	 * Genera un codigo random de 10 caracteres
	 * @return string
	 */
	public function generarCodigo( )
	{
		$this->codigo = substr(md5('dsfgdgh' + microtime()), 0, 10);		
	}
	
	/**
	 * Encripta la clave
	 * @return string
	 */	
	public static function clave ( $clave )
	{
		return md5( '!a8i3Y2P' . $clave);
	}
	
	/**
	 * Genera el codigo interno para resetear la clave
	 * @return $this
	 */	
	public function claveOlvidada ()
	{
		$this->generarCodigo();
		return $this;
	}
	
	/**
	 * @param string clave
	 * @param string codigo
	 * @return $this
	 */	
	public function cambiarClave ( $clave, $codigo )
	{
		if(  $this->codigo != $codigo ){
			throw new Delivery_Model_Exception( Delivery_Model_Exception::USER_INVALID_CODE );	
		}
			
		$this->activo = 1;
		$this->codigo = null;
		$this->setClave($clave);
		
		return $this;
	}
	
	/**
	 * @param string $clave
	 * @return $this
	 */	
	public function setClave( $clave )
	{
		$this->clave  = self::clave($clave);
		return $this;
	}
	
	public function getId()
	{
		return $this->idCliente;
	}
	
	public function getFacebookId()
	{
		return $this->fbUserId;
	}
	
	public function getDirecciones()
	{
		return $this->_direcciones;
	}
	
	public function setDirecciones( $direcciones )
	{
		$this->_direcciones = $direcciones; 
		return $this;
	}
	
	public function isFacebookUser()
	{
		return ! empty( $this->fbUserId );
	}
	
    public function getAvatar()
	{
	    if ( $this->isFacebookUser() ){
	        return "https://graph.facebook.com/{$this->fbUserId}/picture?type=square";
	    } else {
	        $email = md5(strtolower(trim($this->email)));
	        $default = "http://" . $_SERVER['HTTP_HOST'] . "/img/avatar.gif";
	        return "http://www.gravatar.com/avatar/{$email}?f=y&s=60&d=" . urlencode($default);
	    }
	}

}